package com.auxtools;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;

import com.appfront.debug.App;
import com.appfront.TestproSetup;
import com.itextpdf.text.Anchor;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chapter;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;

import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Section;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

public class CreatePDF {

    public static final String FONT = "resources/fonts/NotoSansCJKsc-Regular.otf";
    private static Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD);
    private static Font redFont = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.NORMAL, BaseColor.RED);
    private static Font subFont = new Font(Font.FontFamily.TIMES_ROMAN, 16, Font.BOLD);
    private static Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);
    private static int testGroup = 1;
    private static int testFreqs = 5;
    private static ArrayList<ArrayList<Float>> maxForce;
    private static ArrayList<ArrayList<Float>> maxPower;
    private static ArrayList<ArrayList<Float>> durTimes;

    public static void ManageFile(){
        String path = App.GetSDCardPath();
        File dirFile = new File(path);
        if (!dirFile.exists()){
            return;
        }
        File[] files = dirFile.listFiles();
        for(int i=0; i<files.length; i++){
            if(files[i].isFile()){
                if(files[i].getName().startsWith("-201")){
                    deleteFile(files[i].getAbsolutePath());
                }
            }
        }
//        path = path+"/AppLog/";
//        File logDirFile = new File(path);
//        if (!logDirFile.exists()){
//            return;
//        }
//        File[] logFiles = logDirFile.listFiles();
//        for(int i=0; i<logFiles.length; i++){
//            if(logFiles[i].isFile()){
//                deleteFile(logFiles[i].getAbsolutePath());
//            }
//        }
    }

    public static void CreateFile(Context context, ArrayList<Bitmap> bitmap1, ArrayList<Bitmap> bitmap2, int group,
                                  ArrayList<ArrayList<Float>> max_force, ArrayList<ArrayList<Float>> max_power, ArrayList<ArrayList<Float>> dur_times) {

        testGroup = group;
        testFreqs = TestproSetup.getCurFreqs();
        maxForce = max_force;
        maxPower = max_power;
        durTimes = dur_times;
        if(testGroup > max_force.size())
            testGroup = max_force.size();
        try {
            Document document = new Document(PageSize.A4);
            /* 配置保存名称 */
            SimpleDateFormat sdf = new SimpleDateFormat("-yyyy-MM-dd hh-mm-ss", Locale.getDefault());
            String format = sdf.format(new Date());
            format += ".pdf";


            /* 创建路径 */
            String path = App.GetSDCardPath();
            File file = new File(path);
            if (!file.exists()){
                file.mkdirs();
            }
            FileOutputStream fos = new FileOutputStream(path + TestproSetup.usrID + format);
            PdfWriter.getInstance(document, fos);
            document.open();
            addMetaData(document);
            //addTitlePage(document);
            addContent(document, context, bitmap1, bitmap2);
            document.close();

            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            //officeFile：本地文档；type：文档MIMEType类型，可以使用文件格式后缀
            intent.setDataAndType(Uri.fromFile(new File(path + TestproSetup.usrID + format)), "application/pdf");
            context.startActivity(intent);
        } catch (DocumentException de) {
            System.err.println(de.getMessage());
        } catch (IOException ioe) {
            System.err.println(ioe.getMessage());
        }
    }

    /*  删除单个文件
   * @param   filePath    被删除文件的文件名
    * @return 文件删除成功返回true，否则返回false
   */
    private static boolean deleteFile(String filePath) {
        File file = new File(filePath);
        if (file.isFile() && file.exists()) {
            return file.delete();
        }
        return false;
    }

    private static void addMetaData(Document document) {
        document.addTitle("My first PDF");
        document.addSubject("Using iText");
        document.addKeywords("Java, PDF, iText");
        document.addAuthor("Lars Vogel");
        document.addCreator("Lars Vogel");
    }

    private static void addTitlePage(Document document)
            throws DocumentException {
        Paragraph preface = new Paragraph();
        // We add one empty line
        addEmptyLine(preface, 1);
        // Lets write a big header
        preface.add(new Paragraph("弹力带康复机-测试报告", catFont));

        addEmptyLine(preface, 1);
        // Will create: Report generated by: _name, _date
        preface.add(new Paragraph(
                "Report generated by: " + System.getProperty("user.name") + ", " + new Date(), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                smallBold));

        addEmptyLine(preface, 2);
        preface.add(new Paragraph(
                "This document is a preliminary version and not subject to your license agreement or any other agreement with vogella.de ;-).",
                redFont));

        document.add(preface);
    }

    private static void addContent(Document document, Context context, ArrayList<Bitmap>bitmap1, ArrayList<Bitmap>bitmap2) throws DocumentException, IOException {
        Anchor anchor = new Anchor("弹力带康复机-测试报告", setChineseTiltleFont(12));
        //anchor.setName("ESTIMATING APP");

        // Second parameter is the number of the chapter
        Chapter catPart = new Chapter(new Paragraph(anchor), 1);

        // 第一章，1.1  简介
        Paragraph subPara = new Paragraph("", setChineseTiltleFont(12));
        Section subCatPart = catPart.addSection(subPara);
        subCatPart.add(new Paragraph("用户ID   :  \t" + TestproSetup.usrID,         setChineseFont(12)));
        subCatPart.add(new Paragraph("性别     :  \t" + (TestproSetup.isMale?"男":"女") +
                                           ", 年龄  :  \t" + (TestproSetup.userAge>0?TestproSetup.userAge:"-") + "岁",         setChineseFont(12)));
        subCatPart.add(new Paragraph("身高     :  \t" + (TestproSetup.userHeight>=0?TestproSetup.userHeight:"-") +
                "cm, 体重  :  \t" + (TestproSetup.userWeight>0?TestproSetup.userWeight:"-") + "Kg",         setChineseFont(12)));
        subCatPart.add(new Paragraph("测试组数 :  \t" + testGroup,      setChineseFont(12)));
        subCatPart.add(new Paragraph("每组次数 :  \t" + testFreqs,      setChineseFont(12)));
        for(int i=0; i<testGroup; i++){
            String image1 = saveBitmapFile(context, bitmap1.get(i), 1);
            String image2 = saveBitmapFile(context, bitmap2.get(i), 2);

            Paragraph paragraph1 = new Paragraph();
            addEmptyLine(paragraph1, 1);
            subCatPart.add(paragraph1);
            // 第二章，1.2 内容
            subPara = new Paragraph("测试组: " + Integer.toString(i+1));
            subCatPart = catPart.addSection(subPara);
            subCatPart.add(new Paragraph("表格", setChineseFont(12)));
            // 表格1
            createTable(subCatPart, i);

            Paragraph paragraph2 = new Paragraph();
            addEmptyLine(paragraph2, 1);
            subCatPart.add(paragraph2);
            subCatPart.add(new Paragraph("柱形图：最大拉力+最大功率+峰值持续时间", setChineseFont(12)));
            // 图1
            createImage(subCatPart, image1);
            Paragraph paragraph3 = new Paragraph();
            addEmptyLine(paragraph3, 1);
            subCatPart.add(paragraph3);
            subCatPart.add(new Paragraph("拉力采样", setChineseFont(12)));
            // 图2
            createImage(subCatPart, image2);
        }

        document.add(catPart);
    }

    private static void createImage(Section subCatPart, String imageFilePath) throws IOException, BadElementException {
        Image image = Image.getInstance(imageFilePath);
        image.setAlignment(Element.ALIGN_CENTER);
        image.scaleToFit(400,100);
        subCatPart.add(image);
    }

    private static void createTable(Section subCatPart, int group_index)
            throws BadElementException {
        PdfPTable table = new PdfPTable(testFreqs+1);

        PdfPCell c1 = new PdfPCell(new Phrase("Freqs:"));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);

        for(int i=0; i<testFreqs; i++){
            c1 = new PdfPCell(new Phrase("Test " + Integer.toString(i+1)));
            c1.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(c1);
        }
        table.setHeaderRows(1);

        table.addCell("Force/N");
        for(int i=0; i<testFreqs; i++){
            if(i<maxForce.get(group_index).size())
                table.addCell(String.format("%.1f", maxForce.get(group_index).get(i)));
            else
                table.addCell("");
        }
        table.addCell("Power/W");
        for(int i=0; i<testFreqs; i++){
            if(i < maxPower.get(group_index).size())
                table.addCell(String.format("%.1f", maxPower.get(group_index).get(i)));
            else
                table.addCell("");
        }
        table.addCell("Time/S");
        for(int i=0; i<testFreqs; i++){
            if(i < durTimes.get(group_index).size())
                table.addCell(String.format("%.1f", durTimes.get(group_index).get(i)));
            else
                table.addCell("");
        }
        subCatPart.add(table);
    }

    private static void addEmptyLine(Paragraph paragraph, int number) {
        for (int i = 0; i < number; i++) {
            paragraph.add(new Paragraph(" "));
        }
    }

    public static byte[] bitmap2Bytes(final Bitmap bitmap, final Bitmap.CompressFormat format) {
        if (bitmap == null) return null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(format, 100, baos);
        return baos.toByteArray();
    }

    public static String saveBitmapFile(Context context, Bitmap bitmap, int index){
        SimpleDateFormat sdf = new SimpleDateFormat("-yyyy-MM-dd hh-mm-ss", Locale.getDefault());
        String format = sdf.format(new Date());
        format += ".jpg";

        /* 创建路径 */
        String path = App.GetSDCardPath() + "tmpJPEG/";
        File file = new File(path);
        if (!file.exists()){
            file.mkdirs();
        }
        String filePath = path + index + format;
        try {
            FileOutputStream fos = new FileOutputStream(filePath);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return filePath;
    }

    private static Font setChineseFont() {
        return setChineseFont(12);
    }

    private static Font setChineseFont(int size) {
        Font font = FontFactory.getFont("STSong-Light",
                "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        font.setSize(size);
        return font;
    }

    private static Font setChineseTiltleFont(int size) {
        Font font = FontFactory.getFont("STSong-Light",
                "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        font.setStyle(Font.BOLD);
        font.setSize(size);
        return font;
    }
}
